<template>
  <view>
    <!-- <view @click="toggle('bottom')" style="background-color: red;width: 100px;height: 20px;">{{ label }}</view> -->
    <view style="text-align: right">
      <view @click="toggle()">
        <!-- <text>{{selectedOption[rangeKey]}}</text> -->
        <input
          type="text"
          :value="selectedOption[rangeKey]"
          disabled
          placeholder="请选择"
          style="pointer-events: none; font-size: 15px"
        />
      </view>
    </view>
    <view>
      <!-- 普通弹窗 -->
      <uni-popup
        ref="popup"
        background-color="#fff"
      >
        <view style="
            width: 300px;
            height: 500px;
            background: #fff;
            display: flex;
            justify-content: center;
            border-radius: 15rpx;
            padding: 15rpx;
          ">
          <view>
            <view class="cu-form-group">
              <view class="title">姓名:</view>
              <input
                class="search-input"
                type="text"
                v-model.trim="searchKeyword"
                placeholder="搜索"
              />
            </view>
            <view style="
                height: 400px;
                margin-top: 20rpx;
                padding: 20rpx;
                overflow: auto;
                -webkit-overflow-scrolling: touch;
              ">
              <view
                style="
                  text-align: center;
                  font-size: 30rpx;
                  margin-bottom: 20rpx;
                "
                v-for="(option, index) in filteredOptions"
                :key="index"
                @click="selectOption(option)"
              >
                {{ option[rangeKey] }}
              </view>
              <view
                v-if="filteredOptions.length === 0 && !dataLoading"
                style="
                  text-align: center;
                  font-size: 30rpx;
                  margin-bottom: 20rpx;
                "
              >暂无数据</view>
              <view
                v-if="dataLoading"
                style="
                  text-align: center;
                  font-size: 30rpx;
                  margin-bottom: 20rpx;
                "
              >加载中...</view>
            </view>
          </view>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script>
export default {
  name: 'MySelect',
  props: {
    dictCode: String,
    value: String,
    label: String,
    rangeKey: {
      type: String,
      default: 'label'
    },
    valueKey: {
      type: String,
      default: 'value'
    },
    searchUrl: String,
    isSelect: {
      type: Boolean,
      default: false
    },
    defaultParams: {
      type: Object,
      default: () => {},
      required: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      dictOptions: [],
      selectedOption: {},
      popupVisible: false,
      searchKeyword: '',
      dataLoading: false,
    }
  },
  mounted () {
    this.initDictData();
  },
  methods: {
    initDictData () {
      this.dataLoading = true
      if (this.searchUrl) {
        this.$http.get(this.searchUrl, {
          params: {
            ...(this.defaultParams || {}),
          }
        }).then(res => {
          if (res.data.success) {
            this.dictOptions = res.data.result.records || res.data.result;
            this.selectedOption = this.dictOptions.find(option => option[this.valueKey] === this
              .value) || {};
            this.dataLoading = false
          }
        })
      } else {
        let code = this.dictCode;
        this.$http.get(`/sys/dict/getDictItems/${code}`).then(res => {
          if (res.data.success) {
            console.log('initDictData-noturl', res)
            this.dictOptions = res.data.result;
            this.selectedOption = this.dictOptions.find(option => option[this.valueKey] === this
              .value) || {};
            this.dataLoading = false
          }
        })
      }
    },
    toggle () {
      if (this.disabled) return;
      if (this.isSelect) {
        console.log('isSelect', this.isSelect)
      } else {
        this.searchKeyword = ''
        this.$refs.popup.open('bottom')
      }

    },
    selectOption (option) {
      this.selectedOption = option;
      this.$emit('input', option[this.valueKey]);
      this.$emit("changeItem", option);
      this.$refs.popup.close()
    },
  },
  computed: {
    filteredOptions () {
      if (!this.searchKeyword) return this.dictOptions;
      return this.dictOptions.filter(option => option[this.rangeKey]?.includes(this.searchKeyword));
    }
  }
}
</script>
function debounce(func, wait) {
  let timeout;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      func.apply(context, args);
    }, wait);
  };
}

export default {
  name: "MySelect",
  props: {
    dictCode: String,
    value: String,
    label: String,
    rangeKey: {
      type: String,
      default: "label",
    },
    valueKey: {
      type: String,
      default: "value",
    },
    searchUrl: String,
  },
  data() {
    return {
      dictOptions: [],
      filteredOptions: [],
      selectedOption: {},
      popupVisible: false,
      searchKeyword: "",
      dataLoading: false,
      debounceSearch: null,
    };
  },
  mounted() {
    this.initDictData();
  },
  watch: {
    searchKeyword(newval, oldval) {
      if (this.debounceSearch) {
        clearTimeout(this.debounceSearch);
      }
      this.debounceSearch = debounce(this.updateFilteredOptions, 500);
      this.debounceSearch(newval);
    },
  },
  methods: {
    initDictData() {
      this.dataLoading = true;
      if (this.searchUrl) {
        this.$http
          .get(this.searchUrl, {
            code: this.dictCode,
          })
          .then((res) => {
            if (res.data.success) {
              const result = res.data.result;
              this.dictOptions = result;
              this.filteredOptions = result;
              this.selectedOption =
                result.find((option) => option[this.valueKey] === this.value) ||
                {};
              this.dataLoading = false;
            }
          });
      } else {
        let code = this.dictCode;
        this.$http.get(`/sys/dict/getDictItems/${code}`).then((res) => {
          if (res.data.success) {
            const result = res.data.result;
            this.dictOptions = result;
            this.filteredOptions = result;
            this.selectedOption =
              result.find((option) => option[this.valueKey] === this.value) ||
              {};
            this.dataLoading = false;
          }
        });
      }
    },
    toggle() {
      this.searchKeyword = "";
      this.$refs.popup.open("bottom");
    },
    selectOption(option) {
      this.selectedOption = option;
      this.$emit("input", option[this.valueKey]);
      this.$refs.popup.close();
    },
    updateFilteredOptions(keyword) {
      if (!keyword) {
        this.filteredOptions = this.dictOptions;
      } else {
        this.filteredOptions = this.dictOptions.filter((option) =>
          option[this.rangeKey]?.includes(keyword)
        );
      }
    },
  },
  // computed: {
  // 	filteredOptions() {
  // 		if (!this.searchKeyword) return this.dictOptions;
  // 		return this.dictOptions.filter(option => option[this.rangeKey]?.includes(this.searchKeyword));
  // 	}
  // }
};
</script>

<style lang="scss"></style>
